package org.light.simpleauth.verb;

import java.util.ArrayList;
import java.util.List;

import org.light.core.Verb;
import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.JavascriptBlock;
import org.light.domain.JavascriptMethod;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.Type;
import org.light.easyui.EasyUIPositions;
import org.light.exception.ValidateException;
import org.light.utils.DomainUtil;
import org.light.utils.StringUtil;
import org.light.utils.WriteableUtil;

public class LoginUser extends Verb implements EasyUIPositions {

	@Override
	public Method generateDaoImplMethod() throws Exception {
		return null;
	}	

	@Override
	public Method generateDaoMethodDefinition() throws Exception {
		return null;
	}
	@Override
	public Method generateServiceMethodDefinition() throws Exception {
		return null;
	}
	@Override
	public Method generateServiceImplMethod() throws Exception  {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("Login"+StringUtil.capFirst(this.domain.getStandardName()));
			method.setReturnType(new Type("bool"));		
			method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), new Type(this.domain.getDomainSuffix()+"."+this.domain.getType())));
			method.addAdditionalImport(DomainUtil.packagetokenToGoPackageFolder(this.domain.getProjectName(),this.domain.getPackageToken()+".utils"));
			
			List<Writeable> sList = new ArrayList<Writeable>();
			
			GetSaltUser getSalt = new GetSaltUser(this.domain);
			GetPasswordUser getPassword = new GetPasswordUser(this.domain);
			
			sList.add(new Statement(1000L,1,"db := database.DB"));
			sList.add(new Statement(2000L,1,"salt := "+this.domain.getDaoimplSuffix()+"."+getSalt.getVerbName()+"(db, "+this.domain.getLowerFirstDomainName()+".Get"+this.domain.findFieldByFixedName("userName").getCapFirstFieldName()+"())"));
			sList.add(new Statement(3000L,1,"password := "+this.domain.getLowerFirstDomainName()+".Get"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"()"));
			sList.add(new Statement(4000L,1,"encrypt := utils.MultiSha1(password, salt, 3) "));
			sList.add(new Statement(5000L,1,"dbPassword := "+this.domain.getDaoimplSuffix()+"."+getPassword.getVerbName()+"(db, "+this.domain.getLowerFirstDomainName()+".Get"+this.domain.findFieldByFixedName("userName").getCapFirstFieldName()+"())"));
			sList.add(new Statement(6000L,1,"return encrypt == dbPassword"));
			
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}
		
	public LoginUser(){
		super();
		this.setLabel("登录");
	}
	
	public LoginUser(Domain domain) throws ValidateException{
		super();
		this.domain = domain;
		this.denied = domain.isVerbDenied("LoginUser");
		this.setVerbName("Login"+StringUtil.capFirst(this.domain.getStandardName()));
		this.setLabel("登录");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("LoginUser");
	}

	@Override
	public Method generateControllerMethod() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("Login" + StringUtil.capFirst(this.domain.getStandardName()));
			method.addSignature(new Signature(1,"c","*gin.Context"));
			method.addAdditionalImport(DomainUtil.packagetokenToGoPackageFolder(this.domain.getProjectName(),"pkg.errno"));
			
			method.addAdditionalImport("net/http");
			method.addAdditionalImport("time");	
			
			List<Writeable> sList = new ArrayList<Writeable>();

			sList.add(new Statement(1000L,1,"var form "+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix()+""));
			sList.add(new Statement(2000L,1,"//try get login info"));
			sList.add(new Statement(3000L,1,"if err := c.ShouldBindJSON(&form); err != nil {"));
			sList.add(new Statement(4000L,2,"session.SetFlash(c, \"Get login info error: \"+err.Error())"));
			sList.add(new Statement(5000L,2,"SendResponse(c, nil, nil, 0, false)"));
			sList.add(new Statement(6000L,2,"return"));
			sList.add(new Statement(7000L,1,"}"));
			sList.add(new Statement(8000L,1,"//validate login info"));
			sList.add(new Statement(9000L,1,"loginSuccess := "+this.domain.getServiceimplSuffix()+".Login"+this.domain.getCapFirstDomainName()+"(form)"));
			sList.add(new Statement(10000L,1,"if !loginSuccess {"));
			sList.add(new Statement(11000L,2,"session.SetFlash(c, \"Error : username or password\")"));
			sList.add(new Statement(12000L,2,"SendResponse(c, nil, nil, 0, false)"));
			sList.add(new Statement(13000L,2,"return"));
			sList.add(new Statement(14000L,1,"}"));
			sList.add(new Statement(15000L,1,"//login info is correct, can generate JWT token and store in clien side now"));
			sList.add(new Statement(16000L,1,"tokenString, err := session.GenerateJWTToken(form."+this.domain.findFieldByFixedName("userName").getCapFirstFieldName()+", time.Hour*time.Duration(1))"));
			sList.add(new Statement(17000L,1,"if err != nil {"));
			sList.add(new Statement(18000L,2,"session.SetFlash(c, \"Error Generate token string: \"+err.Error())"));
			sList.add(new Statement(19000L,2,"SendResponse(c, nil, nil, 0, false)"));
			sList.add(new Statement(20000L,2,"return"));
			sList.add(new Statement(21000L,1,"}"));
			sList.add(new Statement(22000L,0,""));
			sList.add(new Statement(23000L,1,"err = session.SetTokenString(c, tokenString, 60*60) //60 minutes"));
			sList.add(new Statement(24000L,1,"if err != nil {"));
			sList.add(new Statement(25000L,2,"session.SetFlash(c, \"Error set token string: \"+err.Error())"));
			sList.add(new Statement(26000L,2,"SendResponse(c, nil, nil, 0, false)"));
			sList.add(new Statement(27000L,2,"return"));
			sList.add(new Statement(28000L,1,"}"));
			sList.add(new Statement(29000L,1,"session.SetFlash(c, \"success : successful login\")"));
			sList.add(new Statement(30000L,1,"session.SetFlash(c, \"username : \"+form."+this.domain.findFieldByFixedName("userName").getCapFirstFieldName()+")"));
			sList.add(new Statement(31000L,1,"c.JSON(http.StatusOK, gin.H{"));
			sList.add(new Statement(32000L,2,"\"data\":    nil,"));
			sList.add(new Statement(33000L,2,"\"token\":   tokenString,"));
			sList.add(new Statement(34000L,2,"\"success\": true,"));
			sList.add(new Statement(35000L,1,"})"));
			sList.add(new Statement(36000L,1,"return"));
			
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}	
	@Override
	public JavascriptBlock generateEasyUIJSButtonBlock() throws Exception {
		return null;		
	}
	@Override
	public JavascriptMethod generateEasyUIJSActionMethod() throws Exception {
		return null;
	}

	@Override
	public Method generateDummyDaoImplMethod() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Method generateDummyServiceImplMethod() throws Exception {
		if (this.denied) return null;
		else {
			Method method = new Method();
			method.setStandardName("Login"+StringUtil.capFirst(this.domain.getStandardName()));
			method.setReturnType(new Type("bool"));		
			method.addSignature(new Signature(1, StringUtil.lowerFirst(this.domain.getStandardName()), new Type(this.domain.getDomainSuffix()+"."+this.domain.getType())));
			method.addAdditionalImport(DomainUtil.packagetokenToGoPackageFolder(this.domain.getProjectName(),this.domain.getPackageToken()+".utils"));
			
			List<Writeable> sList = new ArrayList<Writeable>();
			
			GetSaltUser getSalt = new GetSaltUser(this.domain);
			GetPasswordUser getPassword = new GetPasswordUser(this.domain);
			
			sList.add(new Statement(1000L,1,"db := database.DB"));
			sList.add(new Statement(2000L,1,"salt := "+this.domain.getDaoimplSuffix()+"."+getSalt.getVerbName()+"(db, "+this.domain.getLowerFirstDomainName()+".Get"+this.domain.findFieldByFixedName("userName").getCapFirstFieldName()+"())"));
			sList.add(new Statement(3000L,1,"password := "+this.domain.getLowerFirstDomainName()+".Get"+this.domain.findFieldByFixedName("password").getCapFirstFieldName()+"()"));
			sList.add(new Statement(4000L,1,"encrypt := utils.MultiSha1(password, salt, 3) "));
			sList.add(new Statement(5000L,1,"dbPassword := "+this.domain.getDaoimplSuffix()+"."+getPassword.getVerbName()+"(db, "+this.domain.getLowerFirstDomainName()+".Get"+this.domain.findFieldByFixedName("userName").getCapFirstFieldName()+"())"));
			sList.add(new Statement(6000L,1,"return encrypt == dbPassword"));
			
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}
}
